package hot100;

public class SwapPairs {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode swapPairs(ListNode head) {
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode p = head,pre = preHead;
        while (p != null && p.next != null) {
            ListNode wholeNext = p.next.next;
            ListNode leftToRight = p,rightToLeft = p.next;
            pre.next = rightToLeft;
            rightToLeft.next = leftToRight;
            leftToRight.next = wholeNext;
            pre = leftToRight;
            p = wholeNext;
        }

        return preHead.next;
    }
}
